package com.aisino.efence.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.aisino.efence.enums.FileEnum;
import com.aisino.efence.model.SecretResult;
import com.aisino.efence.service.FileService;
import com.aisino.efence.service.SecretService;
import com.aisino.efence.utils.CompressUtil;
import com.aisino.efence.utils.FTPUtil;
import com.aisino.efence.utils.OkhttpUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileFilter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fzc
 * @package com.aisino.efence.service.impl
 * @create 2018-04-03 13:24
 **/
@Service
public class FileServiceImpl implements FileService {

    private static final Logger LOG = LoggerFactory.getLogger(FileServiceImpl.class);

    @Value("${hubei.msg.url}")
    private String megUrl;
    @Value("${file.path}")
    private String filePath;
    @Autowired
    private SecretService secretService;

    @Override
    public List<File> traverseDirectory(String path) {
        FileFilter fileFilter = file -> {
            if (!file.isFile()) {
                return false;
            }
            if (!file.getName().contains(".csv")) {
                return false;
            }
            return true;
        };
        return FileUtil.loopFiles(path, fileFilter);
    }

    @Override
    public void uploadFile() throws Exception {
        if (hasFile() == 0) {
            //加密
            secretService.encryptFile(filePath + getFileName(FileEnum.EXIST.getCode()), filePath + getFileName(FileEnum.ENCRYPT.getCode()));
        }
        if (hasFile() == 1) {
            //压缩
            CompressUtil.compressFileBy7z(filePath, getFileName(FileEnum.ENCRYPT.getCode()), getFileName(FileEnum.EXIST.getCode()), filePath, getFileName(FileEnum.ZIP.getCode()));
        }
        if (hasFile() == 2) {
            LOG.info("[step 3 上传文件]-[uploadFile]-开始上传文件");
            //上传
            FTPUtil ftpUtil = new FTPUtil();
            ftpUtil.setLocal(new File(filePath + getFileName(FileEnum.ZIP.getCode())));
            ftpUtil.setRemote(getFileName(FileEnum.ZIP.getCode()));
            ftpUtil.upload();
            FileUtil.touch(new File(filePath + getFileName(FileEnum.UPLOAD.getCode())));
            LOG.info("[step 3 上传文件]-[uploadFile]-文件上传完毕");
        }
    }

    @Override
    public void sendMsg() throws Exception {
        if (hasFile() == 3) {
            LOG.info("[step 4 推送通知]-[sendMsg]-开始推送消息");
            Map<String, String> param = new HashMap<>();
            param.put("fileName", getFileName(FileEnum.ZIP.getCode()));
            Response response = OkhttpUtil.okHttpGet(megUrl, param);
            if (null != response) {
                String result = response.body().string();
                LOG.info("[step 4 推送通知]-[sendMsg]-[{}]", result);
                SecretResult secretResult = JSON.parseObject(result, SecretResult.class);
                if (!(secretResult.getCode() == 200)) {
                    throw new RuntimeException("提送消息失败");
                }
            }
            FileUtil.touch(new File(filePath + getFileName(FileEnum.MSG.getCode())));
            LOG.info("[step 4 推送通知]-[sendMsg]-推送消息结束");
        }
    }

    @Override
    public int hasFile() {
        //文件名称 如 20180410
        List<String> fileNames = FileUtil.listFileNames(filePath);
        LOG.info("[step 1 文件检测]-开始文件检测");
        LOG.info("[step 1 文件检测]-搜索到文件[{}]", fileNames);
        if (fileNames.contains(getFileName(FileEnum.MSG.getCode()))) {
            return 4;
        }
        if (fileNames.contains(getFileName(FileEnum.UPLOAD.getCode()))) {
            return 3;
        }
        if (fileNames.contains(getFileName(FileEnum.ZIP.getCode()))) {
            return 2;
        }
        if (fileNames.contains(getFileName(FileEnum.ENCRYPT.getCode()))) {
            return 1;
        }
        if (fileNames.contains(getFileName(FileEnum.EXIST.getCode()))) {
            return 0;
        }
        LOG.info("[step 1 文件检测]-没有搜索到文件");
        return -1;
    }

    private String getFileName(int i) {
        String name = "nuonuo-" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        switch (i) {
            //存在
            case 0:
                return name + ".csv";
            //加密
            case 1:
                return name + ".encrypt";
            //压缩
            case 2:
                return name + ".7z";
            //上传
            case 3:
                return name + ".up";
            //通知
            case 4:
                return name + ".msg";
            default:
                return null;
        }

    }
}
